package org.micode.common.helper;

import org.micode.common.utils.StringExtUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class I18nMsgHelper {

    private static MessageSource messageSource;

    public I18nMsgHelper(MessageSource messageSrc) {
        messageSource = messageSrc;
    }

    /**
     * 获取单个国际化翻译值
     */
    public static String get(String msgKey) {
        try {
            String ret = messageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale());
            if (StringExtUtils.isAnyEmpty(ret)) {
                return msgKey;
            }
            return ret;
        } catch (Exception e) {
            return msgKey;
        }
    }

    /**
     * 获取单个国际化翻译值
     */
    public static String get(String msgKey, String defaultValue) {
        try {
            String ret = messageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale());
            if (StringExtUtils.isAnyEmpty(ret)) {
                return defaultValue;
            }
            return ret;
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * 替换大括号内的键值
     */
    public static String replaceByBraces(String msg) {
        // 取到 msg 中所有{}括起来的键值列表
        List<String> matchList = StringExtUtils.extractMessageByBraces(msg);
        if (matchList.size() > 0) {
            Map<String, Object> valMap = new HashMap<>();
            matchList.forEach(item -> {
                valMap.put(item, get(item));
            });
            return StringExtUtils.format(msg, valMap);
        }
        return msg;
    }

}
